package com.mo.controller;

import com.github.pagehelper.PageInfo;
import com.mo.model.TClue;
import com.mo.query.ClueQuery;
import com.mo.result.R;
import com.mo.service.ClueService;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author mo
 * version
 */
@RestController
public class ClueController {
    @Resource
    ClueService clueService;

    @GetMapping("/api/clues")
    @PreAuthorize(value = "hasAuthority('clue:list')")
    public R cluePage(@RequestParam(value = "current", required = false) Integer current) {
        if (current == null) {
            current = 1;
        }
        PageInfo<TClue> pageInfo = clueService.getClueByPage(current);
        return R.OK(pageInfo);
    }

    @PostMapping(value = "/api/importExcel")
    @PreAuthorize(value = "hasAuthority('clue:import')")
    public R importExcel(MultipartFile file, @RequestHeader(value = "Authorization") String token) throws IOException {
        clueService.importExcel(file.getInputStream(), token);
        return R.OK();
    }

    @GetMapping(value = "/api/clue/{phone}")
    public R checkPhone(@PathVariable(value = "phone") String phone) {
        Boolean check = clueService.checkPhone(phone);
        System.out.println(check);
        return check ? R.OK(200,"成功") : R.OK(499,"失败");
    }

    @PostMapping(value ="/api/clue")
    @PreAuthorize(value = "hasAuthority('clue:add')")
    public R addClue(ClueQuery clueQuery){
       int save = clueService.saveClue(clueQuery);
       return save>=1?R.OK():R.FAIL();
    }

    @GetMapping(value = "/api/clue/load/{id}")
    @PreAuthorize(value = "hasAuthority('clue:view')")
    public R loadClue(@PathVariable(value = "id") Integer id){
        TClue clue= clueService.getClueById(id);
        return R.OK(clue);
    }
    @PutMapping(value = "/api/clue")
    @PreAuthorize(value = "hasAuthority('clue:edit')")
    public R editClue(ClueQuery clueQuery){
        int update= clueService.updateClue(clueQuery);
        return update>0?R.OK():R.FAIL();
    }

    @DeleteMapping("/api/clue/{id}")
    @PreAuthorize(value = "hasAuthority('clue:delete')")
    public R deleteClue(@PathVariable("id") Integer id) {
        int count= clueService.deleteClueById(id);
        return count >= 1 ? R.OK() : R.FAIL();
    }
    @DeleteMapping("/api/clues")
    @PreAuthorize(value = "hasAuthority('clue:delete')")
    public R deleteClues(@RequestParam(value = "ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        int batchDel = clueService.batchDelClueByIds(idList);
        return batchDel >= idList.size() ? R.OK() : R.FAIL();
    }

}